package org.chen.wordwave.init;

import android.app.Application;
import android.content.SharedPreferences;
import android.util.Log;

import com.hjq.toast.Toaster;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.act.VersionManager;
import org.chen.wordwave.bean.ApiResponse;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.bean.Words;
import org.chen.wordwave.bean.WordsDTO;
import org.litepal.LitePal;

import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WordInit extends Application {
    public static SharedPreferences flyerSharedPreferences;
    public static SharedPreferences.Editor flyerEditor;
    public static UserInfo userInfo;

    private static final String TAG = "WordInit";

    public static String baseUrl = "https://wordwave.chen88.top";
    public static String wordsUrl = "https://wordwave.chen88.top";

//    public static String baseUrl = "http://192.168.0.13:7901";
//    public static String wordsUrl = "http://192.168.0.13:7901";
    public static String zhUser = "https://wordprivacy.chen88.top/zh/user.html";
    public static String zhPrivacy = "https://wordprivacy.chen88.top/zh/privacy.html";
    public static String enPrivacy = "https://wordprivacy.chen88.top/en/privacy.html";
    public static String enUser = "https://wordprivacy.chen88.top/en/user.html";
    public static String videoUrl = "https://vfx.mtime.cn/Video/2017/03/31/mp4/170331093811717750.mp4";
    public static String language = "zh";
    public static String message = null;

    @Override
    public void onCreate() {
        super.onCreate();
//        初始化数据库工具
        LitePal.initialize(this);
        Toaster.init(this);
        flyerSharedPreferences = getSharedPreferences("userinfo", MODE_PRIVATE);
        flyerEditor = flyerSharedPreferences.edit();

        userInfo = new UserInfo();

        userInfo.setEmail(flyerSharedPreferences.getString("email", null));
        userInfo.setRegisterTime(flyerSharedPreferences.getString("registerTime", null));
        userInfo.setAccount(flyerSharedPreferences.getString("account", null));
        // 获取设备语言
        language = Locale.getDefault().getLanguage();
        boolean isFirstInstall = flyerSharedPreferences.getBoolean("isFirstInstall", true);

        if (isFirstInstall) {
            // 优先从服务器获取初始化单词数据
            loadInitWordsFromServer();
        }

        checkForWordsUpdate();
    }

    /**
     * 从服务器加载初始化单词数据
     */
    private void loadInitWordsFromServer() {
        ApiService apiService = ApiClient.getClient(this).create(ApiService.class);
        Call<ApiResponse<List<WordsDTO>>> call = apiService.getInitWords();

        call.enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<ApiResponse<List<WordsDTO>>> call,
                                   Response<ApiResponse<List<WordsDTO>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<WordsDTO>> apiResponse = response.body();
                    if (apiResponse.getCode().equals("1000") && apiResponse.getData() != null) {
                        Log.d(TAG, "从服务器成功获取到 " + apiResponse.getData().size() + " 个单词");
                        saveWordsToDatabase(apiResponse.getData());
                        markFirstInstallComplete();
                        return;
                    }
                }
                Log.w(TAG, "服务器响应异常，使用本地默认数据");
                loadDefaultWords();
            }

            @Override
            public void onFailure(Call<ApiResponse<List<WordsDTO>>> call, Throwable t) {
                Log.e(TAG, "网络请求失败，使用本地默认数据: " + t.getMessage());
                loadDefaultWords();
            }
        });
    }

    /**
     * 保存单词数据到本地数据库
     */
    private void saveWordsToDatabase(List<WordsDTO> wordsList) {
        try {
            for (WordsDTO wordDto : wordsList) {
                Words word = new Words(
                        wordDto.getWord(),
                        wordDto.getMeaning(),
                        wordDto.getPronunciation(),
                        wordDto.getImageUrl(), // 使用网络图片地址
                        wordDto.getPrompt()
                );
                word.save();
            }
            Log.d(TAG, "成功保存 " + wordsList.size() + " 个单词到本地数据库");
        } catch (Exception e) {
            Log.e(TAG, "保存单词到数据库失败: " + e.getMessage());
            // 如果保存失败，清除已保存的数据并使用默认数据
            clearWordsDatabase();
            loadDefaultWords();
        }
    }

    /**
     * 清除单词数据库
     */
    private void clearWordsDatabase() {
        try {
            LitePal.deleteAll(Words.class);
            Log.d(TAG, "已清除本地单词数据库");
        } catch (Exception e) {
            Log.e(TAG, "清除单词数据库失败: " + e.getMessage());
        }
    }

    /**
     * 加载默认单词数据（网络失败时的备用方案）
     */
    private void loadDefaultWords() {
        Log.d(TAG, "开始加载本地默认单词数据");
        try {
            // 这里保留原来的本地单词数据作为备用
            new Words("echo", "n.回声;共鸣;", "ˈekəʊ", R.drawable.echo, "The cave echoed with their shouts.\n山洞里回荡着他们的喊声。").save();
            new Words("beneath", "prep.在...之下;", "bɪˈniːθ", R.drawable.beneath, "The submarine dove beneath the waves.\n潜艇潜入海浪之下。").save();
            new Words("gather", "v.收集;聚集;", "ˈɡæðə(r)", R.drawable.gather, "They gathered information from various sources.\n他们从各种来源收集信息。").save();
            new Words("mysterious", "adj.神秘的;不可思议的;", "mɪˈstɪəriəs", R.drawable.word_mysterious, "She told a mysterious story about a haunted house.\n她讲了一个关于闹鬼房子的神秘故事。").save();
            new Words("vivid", "adj.生动的;鲜明的;", "ˈvɪvɪd", R.drawable.vivid, "He gave a vivid description of the event.\n他对事件进行了生动的描述。").save();
            new Words("fragile", "adj.脆弱的;易碎的;", "ˈfrædʒaɪl", R.drawable.fragile, "Handle the fragile items with care.\n小心处理易碎物品。").save();
            new Words("embrace", "v.拥抱;接受;", "ɪmˈbreɪs", R.drawable.embrace, "They embraced each other warmly.\n他们热情地互相拥抱。").save();
            new Words("gloomy", "adj.阴暗的;沮丧的;", "ˈɡluːmi", R.drawable.gloomy, "The room was gloomy and smelled of mold.\n房间阴暗潮湿，有霉味。").save();
            new Words("radiant", "adj.光芒四射的;容光焕发的;", "ˈreɪdiənt", R.drawable.word_radiant, "She looked radiant on her wedding day.\n她在婚礼那天看起来容光焕发。").save();
            new Words("compassion", "n.同情;怜悯;", "kəmˈpæʃn", R.drawable.word_compassion, "He felt great compassion for the homeless.\n他对无家可归者充满了同情。").save();
            new Words("timid", "adj.胆小的;羞怯的;", "ˈtɪmɪd", R.drawable.word_timid, "The timid child hid behind his mother.\n胆小的孩子躲在妈妈后面。").save();
            new Words("abundant", "adj.丰富的;充裕的;", "əˈbʌndənt", R.drawable.word_abundant, "The forest was abundant with wildlife.\n森林中有丰富的野生动物。").save();
            new Words("obstacle", "n.障碍;阻碍;", "ˈɒbstəkl", R.drawable.word_obstacle, "They overcame every obstacle in their path.\n他们克服了道路上的每一个障碍。").save();
            new Words("whisper", "v.低声耳语;轻声细语;", "ˈwɪspə(r)", R.drawable.word_whisper, "She whispered a secret to her friend.\n她悄悄地对朋友说了一个秘密。").save();
            new Words("tranquil", "adj.宁静的;平静的;", "ˈtræŋkwɪl", R.drawable.word_tranquil, "The lake was tranquil and serene.\n湖面宁静祥和。").save();
            new Words("melody", "n.旋律;曲调;", "ˈmelədi", R.drawable.word_melody, "The melody of the song was beautiful.\n这首歌的旋律很美。").save();
            new Words("illuminate", "v.照亮;启发;", "ɪˈluːmɪneɪt", R.drawable.word_illuminate, "The streetlights illuminate the road at night.\n路灯在夜晚照亮道路。").save();
            new Words("oblivious", "adj.遗忘的;未察觉的;", "əˈblɪviəs", R.drawable.word_oblivious, "He was oblivious to the warning signs.\n他没有注意到警告标志。").save();
            new Words("courage", "n.勇气;胆量;", "ˈkʌrɪdʒ", R.drawable.word_courage, "She showed great courage in the face of danger.\n她在危险面前表现出巨大的勇气。").save();
            new Words("serene", "adj.平静的;安详的;", "səˈriːn", R.drawable.word_serene, "The serene landscape calmed her mind.\n宁静的景色使她心情平静。").save();
            new Words("flourish", "v.繁荣;兴旺;", "ˈflʌrɪʃ", R.drawable.word_flourish, "The business continued to flourish.\n生意持续兴旺。").save();
            new Words("delicate", "adj.精致的;脆弱的;", "ˈdelɪkət", R.drawable.word_delicate, "The delicate flowers need careful handling.\n这些娇嫩的花需要小心处理。").save();
            new Words("murmur", "v.低声抱怨;咕哝;", "ˈmɜːmə(r)", R.drawable.word_murmur, "He murmured something under his breath.\n他在嘴里嘀咕了些什么。").save();
            new Words("marvel", "v.感到惊讶;惊叹;", "ˈmɑːvəl", R.drawable.word_marvel, "They marveled at the beauty of the sunset.\n他们惊叹于日落的美景。").save();
            new Words("absorb", "vt.吸收;吸引;吞并,合并;", "əbˈsɔ:rb", org.chen.wordwave.R.drawable.word_absorb, "Plants absorb carbon dioxide\n植物吸收二氧化碳").save();
            new Words("capture", "vt.俘获;夺取;夺得;", "ˈkæptʃə(r)", R.drawable.word_capture, "The incident was captured on videotape \n事件被拍成了录像").save();
            new Words("virus", "n.病毒;病毒性疾病;", "ˈvaɪrəs", R.drawable.word_virus, "The virus seems to have attacked his throat \n病毒看来已经侵蚀到他喉部了。").save();
            new Words("wreck", "n.毁灭，失事;遇难船的残骸;", "rek", R.drawable.word_wreck, "The ship was wrecked by an explosion. \n这艘船被炸毁了").save();
            new Words("accent", "n.口音;重音;腔调;", "ˈæksent", R.drawable.word_accent, "He had developed a slight American accent. \n他说话带上了一点轻微的美国口音。").save();
            new Words("tame", "v.驯服;抑制", "teɪm", R.drawable.word_tame, "After all, he's not a tame lion. \n毕竟他不是只驯服了的狮子。").save();
            new Words("resistant", "adj.有抵抗力的，抵抗的;顽固的", "rɪˈzɪstənt", R.drawable.word_resistant, "The body may be less resistant if it is cold. \n天冷时，身体的抵抗力会下降。").save();
            new Words("undertake", "vt.承诺;保证;承担，从事;", "ˌʌndəˈteɪk", R.drawable.word_undertake, "She undertook the arduous task of monitoring the elections. \n她承担了监督选举的艰巨任务。").save();
            new Words("deny", "vt.拒绝;拒绝承认;", "dɪˈnaɪ", R.drawable.word_deny, "She denied both accusations \n她对两项指控均予以否认。").save();
            new Words("crawl", "vi.爬行;缓慢行进;", "krɔ:l", R.drawable.word_crawl, "I crawled out of bed at nine-thirty \n我9点半才勉强从床上爬起来。").save();
            new Words("mysterious", "adj.玄妙;神秘的，诡秘的;", "mɪˈstɪəriəs", R.drawable.word_mysterious, "He died in mysterious circumstances \n他死得很蹊跷。").save();
            new Words("prevail", "vi.流行，盛行;", "prɪˈveɪl", R.drawable.word_prevail, "We hope that common sense would prevail \n我们希望情理会占上风。").save();
            new Words("token", "n.象征;记号;", "ˈtəʊkən", R.drawable.word_token, "This little gift is a token of our regard. \n这点礼物是我们大家的一点心意。").save();
            new Words("glimpse", "n.一瞥，一看;", "glɪmps", R.drawable.word_glimpse, "I had a glimpse of his true feelings. \n我窥见到他的真实感情。").save();
            new Words("stripe", "n.条纹;种类;", "straɪp", R.drawable.word_stripe, "I have a white head, with a black stripe. \n我有一个白色的头，带黑色条纹。").save();
            new Words("visual", "adj.视觉的，看得见的;", "ˈvɪʒuəl", R.drawable.word_visual, "We work on improving visual acuity. \n我们致力于提高视觉的敏锐度。").save();
            new Words("athlete", "n.运动员;体育家;", "ˈæθli:t", R.drawable.word_athlete, "I was no athlete. \n我根本不是当运动员的料。").save();
            new Words("flesh", "n.肉;肉体;", "fleʃ", R.drawable.word_flesh, "Cut the flesh from the olives and discard the stones. \n把橄榄的果肉切下来，然后去除果核。").save();
            new Words("shear", "vi.剪切;修剪;", "ʃɪə(r)", R.drawable.word_shear, "Trim the shrubs with shears. \n用大剪刀修剪灌木丛。").save();
            new Words("pause", "vi.暂停，中止;", "pɔ:z", R.drawable.word_pause, "He had to pause to clear his throat \n他不得不停顿一下清清嗓子。").save();
            new Words("challenge", "n.挑战，质疑;怀疑;", "ˈtʃæləndʒ", R.drawable.word_challenge, "It was ill-prepared to meet this challenge. \n应对这一挑战明显准备不足。").save();
            new Words("hang", "vi.悬垂;被吊死", "hæŋ", R.drawable.word_hang, "The walls were hung with huge modern paintings. \n墙上挂着巨幅的现代画。").save();
            new Words("reveal", "vt.揭露;泄露;显露;", "rɪˈvi:l", R.drawable.word_reveal, "I shall not reveal the movie's final reel. \n我不会透露该片的结局。").save();
            new Words("ordinary", "adj.普通的;一般的;", "ˈɔ:dnri", R.drawable.word_ordinary, "I'm just a very ordinary, boring normal guy \n我只是一个颇为平庸无趣的普通人。").save();

            markFirstInstallComplete();
            Log.d(TAG, "本地默认单词数据加载完成");
        } catch (Exception e) {
            Log.e(TAG, "加载本地默认单词失败: " + e.getMessage());
        }
    }

    /**
     * 标记首次安装完成
     */
    private void markFirstInstallComplete() {
        flyerEditor.putBoolean("isFirstInstall", false);
        flyerEditor.putLong("wordsInitTime", System.currentTimeMillis());
        flyerEditor.commit();
        Log.d(TAG, "首次安装标记已完成");
    }

    /**
     * 检查是否需要更新单词数据
     */
    public void checkForWordsUpdate() {
        long lastUpdateTime = flyerSharedPreferences.getLong("wordsInitTime", 0);
        long currentTime = System.currentTimeMillis();
        long daysSinceUpdate = (currentTime - lastUpdateTime) / (1000 * 60 * 60 * 24);

        // 如果超过7天，检查服务器是否有更新
        if (daysSinceUpdate > 1) {
            Log.d(TAG, "检查单词数据更新");
            loadInitWordsFromServer();
        }
    }
}
